<template>
  <a-modal v-model:visible="visible" title="Basic Modal" @ok="handleOk" @cancel="handleOk" :afterClose="after"
    beforeOpen="open">
    <a-input v-model:value="form.name" placeholder="Basic usage" />
    <div v-for="item in arr" :key="item.key">{{ item.title }}</div>
    <div v-for="item in arr1" :key="item">{{ item }}</div>
    <sonComponent ref="son"></sonComponent>
    <a-form :model="formState" ref="formRef" name="custom-validation" v-bind="layout">
      <a-form-item has-feedback label="Password" name="pass" v-bind="val.pass">
        <a-input v-model:value="formState.pass" type="password" autocomplete="off" />
      </a-form-item>
      <a-form-item has-feedback label="Confirm" name="checkPass" v-bind="val.checkPass">
        <a-input v-model:value="formState.checkPass" type="password" autocomplete="off" />
      </a-form-item>
      <a-form-item has-feedback label="Age" name="age" v-bind="val.age">
        <a-input-number v-model:value="formState.age" />
      </a-form-item>
      <a-form-item label="url" name="url" v-bind="val['obj.url']">
        <a-input v-model:value="formState.obj.url" />
      </a-form-item>
      <div v-for="(item, i) in formState.list" :key="'item' + i">
        <a-form-item label="name" name="name" v-bind="val[`list[${i}].name`]">
          <a-input :id="item + i" v-model:value="item.name" />
        </a-form-item>
      </div>

      <!-- <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
        <a-button type="primary" html-type="submit">Submit</a-button>
        <a-button style="margin-left: 10px" @click="resetFields">Reset</a-button>
      </a-form-item> -->
    </a-form>
  </a-modal>
</template>
<script>
import { defineComponent, ref, watch, reactive, toRefs, onMounted, getCurrentInstance, toRaw, watchEffect, nextTick } from 'vue';
// import { Rule } from 'ant-design-vue/es/form';
// import { FormInstance } from 'ant-design-vue';
import { Form } from 'ant-design-vue';
import sonComponent from './sonComponent.vue';
const useForm = Form.useForm;
export default defineComponent({
  components: { sonComponent },
  props: {
    visibleShow: {
      type: Boolean,
      default: false
    },
    list: {
      type: Array,
      default: () => []
    },
    setData: {
      type: Object,
      default: null
    }
  },
  emit: ["update:visibleShow", "handleok", "setForm"],
  setup(props, ctx) {
    const visible = ref(false)
    watch(() => props.visibleShow, val => {
      visible.value = val;
    })
    const form = reactive({
      name: ""
    })
    const { list } = toRefs(props)
    const arr = list;
    let arr1 = reactive([]);
    arr1 = [12, 33, 44]
    const son = ref(null)
    const formState = ref({
      pass: '',
      checkPass: '',
      age: undefined,
      obj: {
        url: ""
      },
      list: [{
        name: ""
      }, {
        name: ""
      }]
    });
    const formRef = ref();
    const after = () => {
      // formState.pass = "";
      // formState.checkPass = "";
      // formState.age = "";
      // formState.obj.url = "";
      // formState.list[0].name = "";
      //  formState.list[1].name = "";
      formState.value = {
        pass: '',
        checkPass: '',
        age: undefined,
        obj: {
          url: ""
        },
        list: [{
          name: ""
        }, {
          name: ""
        }]
      }
    }
    let checkAge = async (_rule, value) => {
      if (!value) {
        return Promise.reject('Please input the age');
      }
      if (!Number.isInteger(value)) {
        return Promise.reject('Please input digits');
      } else {
        if (value < 18) {
          return Promise.reject('Age must be greater than 18');
        } else {
          return Promise.resolve();
        }
      }
    };
    let validatePass = async (_rulee, value) => {
      if (value === '') {
        return Promise.reject('Please input the password');
      } else {
        if (formState.checkPass !== '') {
          formRef.value.validateFields('checkPass');
        }
        return Promise.resolve();
      }
    };
    let validatePass2 = async (_rule, value) => {
      if (value === '') {
        return Promise.reject('Please input the password again');
      } else if (value !== formState.value.pass) {
        return Promise.reject("Two inputs don't match!");
      } else {
        return Promise.resolve();
      }
    };

    const rules = reactive({
      pass: [{ required: true, validator: validatePass, trigger: 'change' }],
      checkPass: [{ validator: validatePass2, trigger: 'change' }],
      age: [{ validator: checkAge, trigger: 'change' }],
      'obj.url': [{ required: true, trigger: "change", message: "必填" }],
      'list[0].name': [{ required: true, trigger: "change", message: "必填" }],
      'list[1].name': [{ required: true, trigger: "change", message: "必填" }]
    });

    const { resetFields, validate, validateInfos: val } = useForm(formState, rules);
    const handleOk = () => {
      validate()
        .then(() => {
          visible.value = false;
          ctx.emit("update:visibleShow", false)
          ctx.emit("setForm", JSON.parse(JSON.stringify(toRaw(formState.value))))
        })
        .catch(err => {
          console.log(toRaw(formState));
          console.log('error', err);
        });
    }
    const layout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
    };
    watch(() => props.visibleShow, (val) => {
      console.log(val, 9989)
      if (val && props.setData != null) {
        // console.log(JSON.parse(JSON.stringify(toRaw(props.setData.value))))
        console.log(toRaw(props.setData))
        formState.value =toRaw(props.setData);
        console.log(formState.value)
      }
    })
    return {
      layout,
      arr1,
      arr,
      handleOk,
      visible,
      form,
      after,
      son,
      formState,
      formRef,
      rules,
      resetFields,
      val
    };
  },
});
</script>